<template>
  <div>
    <el-breadcrumb separator="/" style="padding-left:10px;padding-bottom:10px;font-size:12px;">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ this.$router.currentRoute.name }}</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 系统通知列表卡片区 -->
      <!--查询条件区域-->
      <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh">
        <el-row>
          <h4 style="margin: 1vh 0 2vh;color: #1f2d3d">条件查询区</h4>
          <el-form-item>
            操作账户：
            <el-select
                clearable
                style="width: 140px;"
                filterable
                placeholder="请选择操作账户"
                v-model="queryMap.accountName"
                @change="changeAccountName"
            >
              <el-option
                  v-for="(name) in accountName"
                  :key="name"
                  :label="name"
                  :value="name">
              </el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-form-item>
          <el-input
              style="width: 140px;"
              v-model="queryMap.resourceName"
              clearable
              placeholder="请输入客户名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              style="width: 150px;"
              v-model="queryMap.linkman"
              clearable
              placeholder="请输入联系人名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-input
              style="width: 130px;"
              v-model="queryMap.phoneA"
              clearable
              placeholder="请输入电话"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-select
              v-model="queryMap.industryId"
              clearable
              style="width: 140px;"
              placeholder="请选择行业类别"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="IndustryVO in IndustryVOs"
                :label="IndustryVO.options"
                :key="IndustryVO.industryId"
                :value="IndustryVO.industryId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.clientTypeId"
              placeholder="请选择客户种类"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="clientTypeVo in clientTypeVos"
                :label="clientTypeVo.options"
                :key="clientTypeVo.clientTypeId"
                :value="clientTypeVo.clientTypeId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="queryMap.userId" style="width: 140px;" filterable placeholder="请选择归属人">
            <el-option label="全部" value="-1"></el-option>
            <el-option
                v-for="item in options_user"
                :key="item.userId"
                :label="item.nickName+'('+item.userName+')'"
                :value="item.userId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
              clearable
              style="width: 140px;"
              v-model="queryMap.isCall"
              placeholder="是否呼叫"
          >
            <el-option label="全部" value="-1"></el-option>
            <el-option label="否" value="0"></el-option>
            <el-option label="是" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="时间筛选:">
          <el-select
              clearable
              style="width: 120px;"
              v-model="queryMap.time"
              placeholder="请选择时间"
          >
            <el-option label="创建时间" value="1"></el-option>
            <el-option label="呼叫时间" value="2"></el-option>
            <el-option label="更新时间" value="3"></el-option>
          </el-select>
          <el-date-picker
              v-model="value2"
              type="daterange"
              align="right"
              format="yyyy-MM-dd"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button @click="reset" icon="el-icon-refresh">重置</el-button>
          <el-button @click="searchClient()" type="primary" icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
      <!--上方功能模块-->
      <div style="margin-bottom: 10px;display: flex">
        <span class="hint" style="flex: 1;"></span>
        <el-button style="" icon="el-icon-upload"
                   @click="openUpload">导入客户
        </el-button>
        <el-button style="" @click="downloadTemplate"
                   icon="el-icon-download">下载模版
        </el-button>
        <el-button style="" v-hasPermission="'customer:updateIsDelete'" @click="deleteCustomersByIds"
                   icon="el-icon-delete">批量删除
        </el-button>
        <el-button style="" v-hasPermission="'customer:insertHighSeas'" @click="batchTransferToOpenSea"
                   icon="el-icon-position">批量转公海
        </el-button>
        <el-button style="" @click="batchExportExcel" icon="el-icon-download">批量导出</el-button>
        <el-button style="" v-hasPermission="'customer:add'" icon="el-icon-circle-plus-outline"
                   @click="openAddClient()">新增客户
        </el-button>
      </div>
      <!-- 表格区域 -->
      <el-table ref="multipleTable" :data="clientData" size="small" @selection-change="handleSelectionChange"
                border style="width: 100%;" height="420">
        <el-table-column type="selection" width="40"></el-table-column>
        <el-table-column prop="accountName" label="账户" width="100" fixed="left"></el-table-column>
        <el-table-column prop="resourceName" label="客户名称" width="100" fixed="left"></el-table-column>
        <el-table-column prop="linkman" label="联系人" width="100"></el-table-column>
        <el-table-column prop="phoneA" label="电话A" width="160">
          <template v-if="false" v-slot="scope">
            <span>{{ scope.row.phoneA }}</span>
            <el-tooltip content="外呼" placement="top" effect="light">
              <el-button
                  v-hasPermission="'resource:callResource'"
                  icon="el-icon-phone"
                  @click="openCall(scope.row.phoneA)"
                  style="margin-left: 20px;"
                  plain
                  circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="phoneB" label="电话B" width="160">
          <template v-if="false" v-slot="scope">
            <span>{{ scope.row.phoneB }}</span>
            <el-tooltip v-if="scope.row.phoneB && scope.row.phoneB!== ''" content="外呼" placement="top" effect="light">
              <el-button
                  v-hasPermission="'resource:callResource'"
                  icon="el-icon-phone"
                  @click="openCall(scope.row.phoneB)"
                  style="margin-left: 20px;"
                  plain
                  circle
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="clientType" label="客户种类" width="100"></el-table-column>
        <!-- 生命周期列 -->
        <el-table-column label="生命周期" width="100">
          <template slot-scope="scope">
            <!-- 映射数字到对应的生命周期文本 -->
            <span>
          {{
                scope.row.lifeCycle === 0 ? '潜在' :
                    scope.row.lifeCycle === 1 ? '签约' :
                        scope.row.lifeCycle === 2 ? '重复购买' :
                            scope.row.lifeCycle === 3 ? '失效' :
                                '未知'
              }}
        </span>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="客户来源" width="100"></el-table-column>
        <el-table-column prop="industryType" label="行业类型" width="100"></el-table-column>
        <el-table-column prop="nick_name" label="所属人" width="100"></el-table-column>
        <el-table-column prop="lastCallTime" label="最后呼叫时间" width="100"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="100"></el-table-column>
        <el-table-column label="操作" width="380" fixed="right">
          <template v-slot="scope">
            <el-tooltip content="转公海" placement="top" effect="light">
              <el-button type="warning" size="mini" v-hasPermission="'customer:insertHighSeas'"
                         @click="insertHigh_seas_clientList(scope.row.resourceId)" icon="el-icon-position" plain
                         circle></el-button>
            </el-tooltip>
            <el-tooltip style="display: none" content="外呼" placement="top" effect="light">
              <el-button @click="openCall(scope.row.phoneA)" type="success" icon="el-icon-phone" plain
                         circle></el-button>
            </el-tooltip>
            <el-tooltip content="复制微信号" placement="top" effect="light">
              <el-button type="success" icon="el-icon-document-copy" @click="copyPhoneA(scope.row.phoneA)" plain
                         circle></el-button>
            </el-tooltip>
            <el-tooltip content="详情" placement="top" effect="light">
              <el-button type="primary" size="mini" @click="openDetails(scope.row.resourceId)" icon="el-icon-tickets"
                         plain
                         circle></el-button>
            </el-tooltip>
            <el-tooltip content="编辑" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-edit" v-hasPermission="'customer:edit'"
                         @click="openEdit(scope.row.resourceId)" plain
                         circle></el-button>
            </el-tooltip>
            <el-tooltip content="跟进客户" placement="top" effect="light">
              <el-button type="primary" icon="el-icon-link" plain circle
                         @click="openFollow(scope.row.resourceId)"></el-button>
            </el-tooltip>
            <el-tooltip content="添加标签" placement="top" effect="light">
              <el-button type="primary" @click="openLabel(scope.row.resourceId,scope.row.labelId)" size="small"
                         icon="el-icon-circle-plus-outline"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip content="加入黑名单" placement="top" effect="light">
              <el-button type="danger" v-hasPermission="'customer:addBlackList'"

                         @click="openBlacklist(scope.row.resourceName,scope.row.phoneA,scope.row.phoneB)"
                         size="mini" icon="el-icon-s-release"
                         plain circle></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" effect="light">
              <el-button v-hasPermission="'customer:updateIsDelete'" @click="deleteCustomerById(scope.row.resourceId)"
                         type="danger" size="small"
                         icon="el-icon-delete" plain circle></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
          style="margin-top:10px;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryMap.pageNum"
          :page-sizes="this.$globalVar.sizes"
          :page-size="queryMap.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
      ></el-pagination>
      <!-- 导入客户弹出层 -->
      <div v-if="isVisible_upload" class="popups" @click.self="isVisible_upload=false">
        <el-main style="width: 32.5vw;height: 56vh">
          <div class="header">
            <h3 style="flex: 1">导入客户</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="isVisible_upload=false"></el-button>
            </el-tooltip>
          </div>
          <div style="padding-left: 7vh;height: 32vh">
            <el-upload
                class="upload-demo"
                :auto-upload="false"
                drag
                :on-change="handleChange"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :on-error="handleError"
                :file-list="fileList"
                multiple>
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
              <div class="el-upload__tip" slot="tip">只能上传xls,xlsx文件，且不超过5M</div>
            </el-upload>
          </div>
          <el-button type="primary" size="medium" @click="submitUpload" style="margin: 2vh 0 0 43vh;"
                     :loading="btnLoading" :disabled="btnDisabled">确认
          </el-button>
        </el-main>
      </div>
      <!-- 添加标签弹出层 -->
      <div v-if="isVisible_tag" class="popups" @click.self="isVisible_tag=false">
        <el-main style="width: 500px;height: 170px">
          <div class="header">
            <h3 style="flex: 1">标记标签</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="isVisible_tag=false"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-form :inline="true" ref="form" :model="queryMap" size="small" style="margin-top: 2vh">
              <el-form-item>
                <el-select
                    v-model="labelId"
                    clearable
                    style="width: 350px;"
                    placeholder="请选择标签"
                >
                  <el-option
                      v-for="LabelInfoVO in LabelInfoVOs"
                      :label="LabelInfoVO.labelName"
                      :key="LabelInfoVO.labelId"
                      :value="LabelInfoVO.labelId"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button @click="addCustomerLabel" type="primary">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>
      <!-- 跟进客户弹出层 -->
      <div v-if="isVisible_follow" class="popups" @click.self="clearDataAndClose">
        <el-main style="width: 550px;height: 300px">
          <div class="header">
            <h3 style="flex: 1"> 客户</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="closeFollowPopup"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-form :inline="true" ref="form" :model="queryMap" size="small" style="margin-top: 2vh;padding: 2vh 6vh">
              <el-form-item label="跟进内容">
                <el-input
                    v-model="customerFollow.followContent"
                    type="textarea"
                    placeholder="请输入内容"
                    style="width: 40vh"
                    maxlength="200"
                    show-word-limit
                >
                </el-input>
                <span style="color: red"> *</span>
              </el-form-item>
              <el-form-item label="提醒时间">
                <el-date-picker
                    v-model="customerFollow.remindTime"
                    type="date"
                    placeholder="选择日期">
                </el-date-picker>
              </el-form-item>

              <el-form-item style="margin-left:2vh">
                <el-button :loading="btnLoading" :disabled="btnDisabled" @click="addCustomerFollow" type="primary">
                  保存
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>
      <!-- 黑名单弹出层 -->
      <div v-if="isVisible_blacklist" class="popups" @click.self="clearBlacklist">
        <el-main style="width: 550px; height: 350px">
          <div class="header">
            <h3 style="flex: 1">加入黑名单客户</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button icon="el-icon-circle-close" circle @click="clearBlacklist"></el-button>
            </el-tooltip>
          </div>
          <div>
            <el-form :inline="true" ref="form" size="small" style="margin-top: 2vh; padding: 2vh 6vh">
              <el-form-item label="选择号码">
                <el-checkbox checked v-model="blacklist.selectedClientPhone" :true-label="blacklist.clientPhone"
                             :false-label="''">
                  电话A：{{ blacklist.clientPhone }}
                </el-checkbox>
                <el-checkbox v-if="blacklist.clientPhoneB" v-model="blacklist.selectedClientPhoneB"
                             :true-label="blacklist.clientPhoneB" :false-label="''"
                >
                  电话B：{{ blacklist.clientPhoneB }}
                </el-checkbox>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                    v-model="blacklist.remark"
                    type="textarea"
                    placeholder="请输入备注"
                    style="width: 40vh"
                    maxlength="200"
                    show-word-limit
                ></el-input>
              </el-form-item>
              <el-form-item style="margin-left:2vh">
                <el-button :loading="btnLoading" :disabled="btnDisabled" @click="addBlackList" type="primary">保存
                </el-button>
              </el-form-item>
            </el-form>
          </div>
        </el-main>
      </div>
      <!-- 新增客户弹出层 -->
      <div v-if="isVisible_add" class="popups" @click.self="closeAddCustomer">
        <el-main style="width: 850px;background-color: #f0f0f0">
          <div class="header">
            <h3 style="flex: 1">新增客户</h3>
            <el-tooltip content="关闭页面" placement="top" effect="light">
              <el-button style="background-color: #f0f0f0" icon="el-icon-circle-close" circle
                         @click="closeAddCustomer"></el-button>
            </el-tooltip>
          </div>
          <el-card style="margin: 0 3vh 3vh; padding-top: 3vh">
            <el-form :model="addCustomerObject" :rules="formRules" ref="form" size="small">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="客户名称:" prop="resourceName" required>
                    <el-input
                        style="width: 232px;"
                        v-model="addCustomerObject.resourceName"
                        clearable
                        placeholder="请输入客户名称"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系人:" prop="linkman" required>
                    <el-input
                        style="width: 232px;"
                        v-model="addCustomerObject.linkman"
                        clearable
                        placeholder="请输入联系人名称"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="电话A:" style="margin-left: 2.2vh" prop="phoneA" required>
                    <el-input
                        style="width: 232px;"
                        v-model="addCustomerObject.phoneA"
                        clearable
                        placeholder="请输入电话A"
                    ></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="电话B:" style="margin-left: .7vh" prop="phoneB">
                    <el-input
                        style="width: 232px;"
                        v-model="addCustomerObject.phoneB"
                        clearable
                        placeholder="请输入电话B"
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="8">
                  <el-form-item label="行业类别" style="margin-left: .3vh" prop="industryId">
                    <el-select
                        clearable
                        v-model="addCustomerObject.industryId"
                        style="width: 130px;"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="IndustryVO in IndustryVOs"
                          :label="IndustryVO.options"
                          :key="IndustryVO.industryId"
                          :value="IndustryVO.industryId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="客户状态" prop="clientStatusId">
                    <el-select
                        clearable
                        style="width: 130px;"
                        v-model="addCustomerObject.clientStatusId"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="clientStatusVO in clientStatusVOs"
                          :label="clientStatusVO.options"
                          :key="clientStatusVO.clientStatusId"
                          :value="clientStatusVO.clientStatusId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="来源" prop="sourceId">
                    <el-select
                        clearable
                        v-model="addCustomerObject.sourceId"
                        style="width: 130px;"
                        placeholder="请选择"
                    >
                      <el-option
                          v-for="sourceVO in sourceVOs"
                          :label="sourceVO.options"
                          :key="sourceVO.sourceId"
                          :value="sourceVO.sourceId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="备注:" style="margin-left: 3.5vh" prop="remark">
                    <el-input
                        type="textarea"
                        placeholder="请输入内容"
                        v-model="addCustomerObject.remark"
                        style="width: 74vh"
                        maxlength="200"
                        show-word-limit
                    ></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24">
                  <el-form-item style="margin-left: 67.5vh">
                    <el-button @click="closeAddCustomer">取消</el-button>
                    <el-button
                        :loading="btnLoading"
                        :disabled="btnDisabled"
                        @click="addCustomer" type="primary">保存
                    </el-button>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-main>
      </div>
      <!-- 详情抽屉 -->
      <el-drawer
          title="客户详情"
          :visible.sync="drawer_details"
          direction="rtl"
          size="60%"
      >
        <div style="text-align: center;color: #1f2d3d">
          <h2 style="margin: 0" v-text="clientObject.resourceName">客户名称</h2>
          <div style="color: #5e6d82;font-size: 14px; margin-bottom: 3vh">创建时间:
            <span v-text="clientObject.createTime"></span>
          </div>

        </div>
        <div style="height: 70vh;overflow: auto">
          <el-card style="margin: 0 3vh">
            <el-row>
              <el-col :span="24" style="color: #1a73e8">基本信息</el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>联系人:</label><span v-text="clientObject.linkman"></span>
              </el-col>
              <el-col :span="8">
                <label>联系电话A:</label><span v-text="clientObject.phoneA"></span>
              </el-col>
              <el-col :span="8">
                <label>联系电话B:</label><span v-text="clientObject.phoneB"></span>
              </el-col>

            </el-row>
            <el-row>
              <el-col :span="8">
                <label>行业类别:</label><span v-text="clientObject.industryType"></span>
              </el-col>
              <el-col :span="8">
                <label>客户种类:</label><span v-text="clientObject.clientType"></span>
              </el-col>

              <el-col :span="8">
                <label>生命周期:</label> <span>
                  {{
                  clientObject.lifeCycle === 0 ? '潜在' :
                      clientObject.lifeCycle === 1 ? '签约' :
                          clientObject.lifeCycle === 2 ? '重复购买' :
                              clientObject.lifeCycle === 3 ? '失效' :
                                  '未知'
                }}</span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <label>客户来源:</label><span v-text="clientObject.source"></span>
              </el-col>
              <el-col :span="8">
                <label>客户状态:</label><span v-text="clientObject.clientStatus"></span>
              </el-col>
              <el-col :span="8">
                <label>客户标签:</label><span v-text="clientObject.labelName"></span>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <label>备注:</label><span v-text="clientObject.remark"></span>
              </el-col>
            </el-row>
          </el-card>
          <el-card style="margin: 3vh">
            <el-row>
              <el-col :span="24" style="color: #1a73e8">跟进时间线</el-col>
            </el-row>
            <div class="block">
              <el-timeline>
                <el-timeline-item
                    v-for="(item, index) in CustomerFollowList"
                    :key="index"
                    :timestamp="item.followTime.slice(0, 10)"
                    placement="top">
                  <el-card>
                    <h4>{{ item.followContent }}</h4>
                    <p>{{ item.nick_name }} 提交于 {{ item.followTime.slice(0, 16) }}</p>
                  </el-card>
                </el-timeline-item>
              </el-timeline>
            </div>
          </el-card>
        </div>
      </el-drawer>
      <!-- 编辑抽屉 -->
      <el-drawer
          title="编辑客户信息"
          :visible.sync="drawer_edit"
          direction="rtl"
          size="60%"
          @close="handleDrawerClose"
      >
        <el-card style="margin: 0 3vh">
          <el-row>
            <el-col :span="24" style="color: #1a73e8">基本信息</el-col>
          </el-row>
          <el-form :rules="formRules" :model="clientObject" :inline="true" ref="clientObject" size="small">
            <el-row>
              <el-col :span="8">
                <el-form-item prop="resourceName" label="客户名称:">
                  <el-input
                      v-model="clientObject.resourceName"
                      style="width: 140px;"
                      clearable
                      placeholder="请输入客户名称"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item prop="phoneA" label="联系电话A:">
                  <el-input
                      v-model="clientObject.phoneA"
                      style="width: 140px;"
                      clearable
                      placeholder="请输入联系电话A"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="联系电话B:" prop="phoneB">
                  <el-input
                      v-model="clientObject.phoneB"
                      style="width: 140px;"
                      clearable
                      placeholder="请输入联系电话B"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="行业类别:">
                  <el-select
                      v-model="clientObject.industryId"
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                  >
                    <el-option
                        v-for="IndustryVO in IndustryVOs"
                        :label="IndustryVO.options"
                        :key="IndustryVO.industryId"
                        :value="IndustryVO.industryId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户种类:">
                  <el-select
                      v-model="clientObject.clientTypeId"
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                  >
                    <el-option
                        v-for="clientTypeVo in clientTypeVos"
                        :label="clientTypeVo.options"
                        :key="clientTypeVo.clientTypeId"
                        :value="clientTypeVo.clientTypeId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="客户状态:">
                  <el-select
                      v-model="clientObject.clientStatusId"
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                  >

                    <el-option
                        v-for="clientStatusVO in clientStatusVOs"
                        :label="clientStatusVO.options"
                        :key="clientStatusVO.clientStatusId"
                        :value="clientStatusVO.clientStatusId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="8">
                <el-form-item label="客户来源:">
                  <el-select
                      v-model="clientObject.sourceId"
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                  >
                    <el-option
                        v-for="sourceVO in sourceVOs"
                        :label="sourceVO.options"
                        :key="sourceVO.sourceId"
                        :value="sourceVO.sourceId"
                    >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="生命周期:">
                  <el-select
                      v-model="clientObject.lifeCycle"
                      clearable
                      style="width: 140px;"
                      placeholder="请选择"
                  >
                    <el-option :value="0" label="潜在"></el-option>
                    <el-option :value="1" label="签约"></el-option>
                    <el-option :value="2" label="重复购买"></el-option>
                    <el-option :value="3" label="失效"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注:" style="margin-left: 3.5vh">
                  <el-input
                      v-model="clientObject.remark"
                      type="textarea"
                      placeholder="请输入内容"
                      style="width: 88vh"
                      maxlength="200"
                      show-word-limit
                  >
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-button :loading="btnLoading" :disabled="btnDisabled" @click="editCustomer" type="primary"
                         style="margin: 0 44vh" size="big">保存
              </el-button>
            </el-row>
          </el-form>
        </el-card>

      </el-drawer>
    </el-card>
  </div>
</template>
<script>
import axios from "axios";
import ElectUsersBox from "@/components/electUsersBox.vue";

export default {
  components: {ElectUsersBox},
  data() {
    return {
      //外呼
      appId: "",
      callerNbr: "",
      calleeNbr: "",
      bindNbr: "",
      notifyUrl: "http://47.99.186.44:8990/comcentre/call/callBackSaveLog",//回拨接口ip：port 换成上线的服务器
      sign: "",
      btnLoading: false,
      btnDisabled: false,
      value: "",
      isVisible_upload: false,//导入标签弹出层是否展示
      isVisible_tag: false,//添加标签弹出层是否展示
      isVisible_add: false,//新增客户弹出层是否展示
      isVisible_follow: false,//客户跟进弹出层是否展示
      isVisible_blacklist: false,
      radio: '未标记',//抽屉中资源标签选项
      drawer_details: false,//详情抽屉是否显示
      drawer_edit: false,//编辑抽屉是否显示
      total: 0,
      multipleSelection: [],
      labelId: null,
      //添加客户数据
      addCustomerObject: {
        resourceName: '',
        linkman: '',
        phoneA: '',
        phoneB: '',
        industryId: null,
        clientStatusId: null,
        sourceId: null,
        remark: '',
      },
      //黑名单数据
      blacklist: {
        clientName: '',
        clientPhone: '',
        clientPhoneB: '',
        selectedClientPhone: '',
        selectedClientPhoneB: '',
        remark: ''
      },
      formRules: {
        resourceName: [
          {required: true, message: '客户名称不能为空，亲，请填写！', trigger: 'blur'}
        ],
        linkman: [
          {required: true, message: '联系人不能为空，亲，请填写！', trigger: 'blur'}
        ],
        phoneA: [
          {required: true, message: '电话A不能为空，亲，请填写有效的电话A！', trigger: 'blur'},
          {
            pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/,
            message: '请输入有效的手机号码',
            trigger: 'blur'
          }
        ],
        phoneB: [
          {required: false, message: '如需填写，请填写有效的电话B！', trigger: 'blur'},
          {
            pattern: /^(?:\+86|0086)?\s*-?\s*(?:(?:1[3-9]\d{9})|(?:0\d{2,3}-\d{7,8})|(?:0\d{10}))$/,
            message: '如需填写，请输入有效的手机号码',
            trigger: 'blur'
          }
        ],
      },
      accountName: [],
      clientData: [],
      IndustryVOs: [],
      clientTypeVos: [],
      sourceVOs: [],
      clientStatusVOs: [],
      LabelInfoVOs: [],
      options_user: [],
      resourceId: '',   //客户编号
      value2: [],//日期选择器
      //添加客户跟进数据
      customerFollow: {
        resourceId: null,
        followContent: '',
        remindTime: '',
        // followTime: '',
        // remark: '',
      },
      //详情客户数据
      clientObject: {
        resourceName: '',
        createTime: '',
        linkman: '',
        phoneA: '',
        phoneB: '',
        industryType: '',
        clientType: '',
        source: '',
        clientStatus: '',
        remark: '',
        industryId: null,
        clientTypeId: null,
        clientStatusId: null,
        sourceId: null,
        lifeCycle: null,
        labelName: '',
        labelId: null, //标签编号
      },
      // 客户跟进数据
      CustomerFollowList: [],
      //查询对象
      queryMap: {
        pageNum: 1,
        pageSize: 10,
        resourceName: "",
        linkman: "",
        phoneA: "",
        industryId: "",
        clientTypeId: "",
        userId: "",
        isCall: "",
        time: '1',
        startTime: "",
        endTime: "",
        accountName: ''
      },
      //时间选择器
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
      durationOptions: {
        0: "1秒",
        1: "20秒",
        2: "30秒",
        3: "40秒",
        4: "50秒",
        5: "60秒",
        6: "70秒",
        7: "80秒",
        8: "90秒",
        9: "100秒",
        10: "110秒",
        11: "120秒",
        12: "120秒以上",
      },
      // 上传文件列表
      fileList: [],
      excelFile: {},
    };
  },
  methods: {
    //导入客户弹出层
    openUpload(){
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        this.isVisible_upload = true;
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    //账户发生改变
    changeAccountName() {
      this.getClientList();
      this.getAllIndustryList();
      this.getAllClientType();
      this.getAllSource();
      this.getAllClientStatus();
    },
    //重置
    reset() {
      this.queryMap = {
        pageNum: 1,
        pageSize: 10,
        resourceName: "",
        linkman: "",
        phoneA: "",
        industryId: "",
        clientTypeId: "",
        userId: "",
        isCall: "",
        time: '1',
        startTime: "",
        endTime: "",
        accountName: ''
      };
      this.defaultTime();
      this.getClientList();
    },
    //打开新增客户
    openAddClient() {
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        this.isVisible_add = true;
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    //打开详情抽屉
    openDetails(id) {
      this.clearClientObject
      this.resourceId = id;
      this.getClientById();
      this.getCustomerFollow();
      this.drawer_details = true;
    },
    //打开修改抽屉
    openEdit(id) {
      // 可以清空表单数据
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        this.clearClientObject
        this.drawer_edit = true;
        this.resourceId = id;
        this.getClientById();
        this.$refs.clientObject.resetFields();
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    //打开客户标签抽屉
    openLabel(id, labelId) {
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        this.isVisible_tag = true;
        this.labelId = labelId
        this.resourceId = id;
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    //打开客户跟进抽屉
    openFollow(id) {
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        if (typeof id === 'undefined') {
          console.error('id is undefined when opening drawer');
          return;
        }
        this.isVisible_follow = true;
        this.customerFollow.resourceId = id;
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    //打开黑名单抽屉
    openBlacklist(clientName, clientPhone, clientPhoneB) {
      let accountName = this.queryMap.accountName
      if (accountName != null && accountName !== "") {
        this.blacklist.clientName = clientName;
        this.blacklist.clientPhone = clientPhone;
        this.blacklist.clientPhoneB = clientPhoneB;
        this.isVisible_blacklist = true
      } else {
        this.$message.warning("请先选择账户！！！")
      }
    },
    // 提交上传文件
    async submitUpload() {
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("file", this.excelFile.raw);
      this.btnLoading = true;
      this.btnDisabled = true;
      const config = {
        params: {
          accountName: this.queryMap.accountName
        },
        headers: {
          "Content-Type": "multipart/form-data" // 确保是多部分请求
        }
      };
      const { data: res } = await this.$http.post("/customer/importClient", formData, config);
      if (res.success) {
        this.$notify.success({
          title: '操作成功',
          message: 'excel文件上传成功'
        });
        // 调用查询方法
        await this.getClientList();
      } else {
        this.isVisible_upload = false;
        this.btnLoading = false;
        this.btnDisabled = false;
        return this.$message.error("excel文件上传失败:" + res.data.errorMsg);
      }
      // 关闭上传弹出层
      this.isVisible_upload = false;
      // 清空抽屉文件集合
      this.fileList = [];
      this.excelFile = {};
      this.btnLoading = false;
      this.btnDisabled = false;
    },
    //外呼按钮点击事件
    openCall(phoneA) {
      this.calleeNbr = phoneA
      this.outPhone();
    },
    //加载客户列表
    async getClientList() {
      const {data: res} = await this.$http.get(
          "customer/findList",
          {
            params: this.queryMap
          }
      );
      if (!res.success) {
        return this.$message.error("获取用户列表失败:" + res.data.errorMsg);
      } else {
        this.total = res.data.total;
        this.clientData = res.data.rows;
      }
    },
    //修改客户
    async editCustomer() {
      const valid = await this.$refs.clientObject.validate();
      if (valid) {
        this.btnLoading = true;
        this.btnDisabled = true;
        const response = await this.$http.put("customer/editCustomerById", this.clientObject);
        if (response.data.data === 1) {
          this.$message.success('客户修改成功');
          this.btnLoading = false;
          this.btnDisabled = false;
          this.getClientList(); // 获取客户列表
          this.drawer_edit = false; // 关闭抽屉
        } else if (response.data.data === -1) {
          this.$message.warning("电话号码已存在！");
          this.btnLoading = false
          this.btnDisabled = false
        } else {
          this.$message.error(response.data.message);
        }
      } else {
        this.$message.error('请检查必填字段');
        this.btnLoading = false;
        this.btnDisabled = false;
      }
    },
    //添加客户标签
    async addCustomerLabel() {
      // 发送 PUT 请求到后端
      const labelId = this.labelId
      if (labelId != null && labelId != '') {
        const response = await this.$http.put("customer/addCustomerLabel", {
          resourceId: this.resourceId,
          labelId: this.labelId
        })
        // 判断响应
        if (response.data.success == 1) {
          // 修改成功
          this.$message.success('添加标签成功！');
          this.getClientList();
          this.isVisible_tag = false
        } else {
          // 修改失败
          this.$message.error(response.data.message);
        }
      } else {
        this.$message.error("请选择标签");
      }
    },
    //获取客户详情
    async getClientById() {
      const {data: res} = await this.$http.get(
          "customer/getClientById", {
            params: {resourceId: this.resourceId}
          }
      );
      console.log(this.resourceId)
      if (!res.success) {
        return this.$message.error("获取客户详情失败:" + res.data.errorMsg);
      } else {
        this.clientObject = res.data
      }
    },
    //获取客户跟进详情
    async getCustomerFollow() {
      const {data: res} = await this.$http.get(
          "customer/getCustomerFollowByClientId", {
            params: {resourceId: this.resourceId}
          }
      );
      if (!res.success) {
        return this.$message.error("获取客户跟进详情失败:" + res.data.errorMsg);
      } else {
        this.CustomerFollowList = res.data
      }
    },
    //删除客户
    async deleteCustomerById(id) {
      //弹出确认框，询问用户是否确认删除
      const confirmResult = await this.$confirm('确认要删除该客户吗？', '删除提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消删除操作');
      })
      if (confirmResult) {
        // 发送修改请求，传递一个包含 resourceId 的对象
        const response = await this.$http.put(
            "customer/deleteCustomerById", {
              resourceIds: [id]
            }
        );
        if (response.data.data > 0) {
          this.$message.success('删除成功');
          // 更新列表或执行其他操作
          this.getClientList();
        } else {
          this.$message.error('删除失败：' + res.data.errorMsg);
        }
      }
    },
    //批量删除客户
    async deleteCustomersByIds() {
      // 将选中的客户 ID 包装成数组
      const payload = this.multipleSelection.map(item => item.resourceId); // 获取选中的客户 ID 数组
      if (payload.length > 0) {
        // 弹出确认框，询问用户是否确认删除
        const confirmResult = await this.$confirm('确认要批量删除该客户吗？此操作不可恢复，请谨慎操作', '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(() => {
          this.$message.info('已取消删除操作');
        })
        if (confirmResult) {
          // 发送批量删除请求
          const response = await this.$http.put("customer/deleteCustomerById", {
                resourceIds: payload
              }
          )
          if (response.data.data > 0) {
            this.$message.success(`删除成功，共成功删除 ${response.data.data} 个客户`);
            // 更新列表或执行其他操作
            this.getClientList();
          } else {
            this.$message.error('删除失败，没有客户被成功删除');
          }
        }
      } else {
        this.$message.error("您没有选择客户");
      }
    },
    //新增客户
    async addCustomer() {
      // 手动触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.btnLoading = true
          this.btnDisabled = true
          const config = {
            params: {
              accountName: this.queryMap.accountName
            }
          };
          // 如果验证通过，发送请求
          this.$http.post("customer/addCustomer", this.addCustomerObject,config)
              .then(response => {
                if (response.data.data === 1) {
                  this.$message.success('添加客户成功！');
                  this.btnLoading = false
                  this.btnDisabled = false
                  this.closeAddCustomer();
                  this.getClientList();
                  // 可以清空表单数据
                  this.$refs.form.resetFields();
                } else if (response.data.data === -1) {
                  this.$message.warning("电话号码已存在！");
                  this.btnLoading = false
                  this.btnDisabled = false
                } else {
                  this.$message.error(response.data.message);
                  this.btnLoading = false
                  this.btnDisabled = false
                }
              })
        } else {
          // 如果验证不通过，显示错误信息
          this.$message.error('请填写所有必填项，或正确填写信息');
          this.btnLoading = false
          this.btnDisabled = false
          return false;
        }
      });
    },
    //加入黑名单
    async addBlackList() {
      const blacklist = this.blacklist;
      this.btnLoading = true
      this.btnDisabled = true
      if (!this.blacklist.selectedClientPhone && !this.blacklist.selectedClientPhoneB) {
        this.$message.warning("请选择至少一个号码");
        this.btnLoading = false
        this.btnDisabled = false
        return;
      }
      try {
        const config = {
          params: {
            accountName: this.queryMap.accountName
          }
        };
        const response = await this.$http.post("customer/addBlackList", blacklist,config);
        // 判断后端返回的data字段的值是否为1，表示成功
        console.log(response.data)
        if (response.data.data > 0) {
          this.$message.success('添加黑名单成功！');
          this.btnLoading = false
          this.btnDisabled = false
          this.clearBlacklist();
          this.isVisible_follow = false;
        } else {
          this.$message.error('该客户已存在黑名单！');
          this.btnLoading = false
          this.btnDisabled = false
          this.clearBlacklist();
          this.isVisible_follow = false;
        }
      } catch (error) {
        console.error(error);
        this.$message.error('请求失败，请稍后再试');
        this.btnLoading = false
        this.btnDisabled = false
      }
    },
    //添加客户跟进
    async addCustomerFollow() {
      this.btnLoading = true;
      this.btnDisabled = true;
      const isOk = this.customerFollow.followContent != null && this.customerFollow.followContent != ''
      if (isOk) {
        if (this.customerFollow.remindTime != null && this.customerFollow.remindTime != '') {
          this.customerFollow.remindTime = this.formatToMySQLDate(this.customerFollow.remindTime);
        }
        const config = {
          params: {
            accountName: this.queryMap.accountName
          }
        };
        const response = await this.$http.post("customer/addCustomerFollow", this.customerFollow,config)
        console.log(this.customerFollow.remindTime)
        if (response.data.success == 1) {
          this.$message.success('添加客户跟进成功！');
          this.btnLoading = false;
          this.btnDisabled = false;
          this.clearCustomerFollow();
          this.isVisible_follow = false
        } else {
          this.btnLoading = false;
          this.btnDisabled = false;
          this.$message.error(response.data.message);
        }
      } else {
        this.btnLoading = false;
        this.btnDisabled = false;
        this.$message.error("请输入完整信息");
      }
    },
    //关闭抽屉时清除表单验证错误
    handleDrawerClose() {
      this.$refs.form.clearValidate(); // 清除验证错误
    },
    //关闭添加页面
    closeAddCustomer() {
      this.isVisible_add = false
      this.clearAddCustomer();
    },
    //重置表单数据
    clearAddCustomer() {
      this.$refs.form.resetFields();  // 重置表单
      this.addCustomerObject = {
        resourceName: '',
        linkman: '',
        phoneA: '',
        phoneB: '',
        industryId: null,
        clientStatusId: null,
        sourceId: null,
        remark: '',
      };  // 清空数据
    },
    //清空客户跟进表单数据
    clearCustomerFollow() {
      this.customerFollow = {
        resourceId: null,
        followContent: '',
        remindTime: '',  // 清空提醒时间
      };
    },
    //关闭弹窗
    closeFollowPopup() {
      this.clearCustomerFollow();  // 清空数据
      this.isVisible_follow = false;  // 关闭弹窗
    },
    //点击空白区域时关闭弹窗并清空数据
    clearDataAndClose() {
      this.clearCustomerFollow();  // 清空数据
      this.isVisible_follow = false;  // 关闭弹窗
    },
    //清除黑名单数据
    clearBlacklist() {
      this.blacklist = {
        clientName: '',
        clientPhone: '',
        clientPhoneB: '',
        selectedClientPhone: '',
        selectedClientPhoneB: '',
        remark: '',
      }
      //关闭弹出层
      this.isVisible_blacklist = false
    },
    //清除ClientObject
    clearClientObject() {
      this.clientObject = {
        resourceName: '',
        createTime: '',
        linkman: '',
        phoneA: '',
        phoneB: '',
        industryType: '',
        clientType: '',
        source: '',
        clientStatus: '',
        remark: '',
        industryId: null,
        clientTypeId: null,
        clientStatusId: null,
        sourceId: null,
        lifeCycle: null,
        labelName: '',
        labelId: null, //标签编号
      }
    },
    //加载行业类型列表
    async getAllIndustryList() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findIndustryVOList", {
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.IndustryVOs = validData.map(item => ({
          industryId: item.industryId,
          options: item.options
        }));
      }
    },
    //加载客户类型列表
    async getAllClientType() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findClientTypeVOList", {
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.clientTypeVos = validData.map(item => ({
          clientTypeId: item.clientTypeId,
          options: item.options
        }));
      }
    },
    //获取所有账户
    async getAccountNameList() {
      const {data: res} = await this.$http.get("/system/user/qt/findRoleList");
      if (!res.success) {
        return this.$message.error("获取角色信息失败:" + res.data);
      }
      this.accountName = res.data

    },
    //加载客户来源列表
    async getAllSource() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findSourceVOList", {
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.sourceVOs = validData.map(item => ({
          sourceId: item.sourceId,
          options: item.options
        }));
      }
    },
    //加载客户状态列表
    async getAllClientStatus() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findClientStatusVOList", {
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.clientStatusVOs = validData.map(item => ({
          clientStatusId: item.clientStatusId,
          options: item.options
        }));
      }
    },
    //加载标签列表
    async getAllLabelInfo() {
      this.loading = true;
      const {data: res} = await this.$http.get("/customer/findLabelInfoVOList",{
        params: {accountName: this.queryMap.accountName}
      });
      let validData = [];
      if (Array.isArray(res)) {
        validData = res;
      } else if (typeof res === 'object' && res.success) {
        validData = res.data || [];
      }
      if (Array.isArray(validData)) {
        this.LabelInfoVOs = validData.map(item => ({
          labelId: item.labelId,
          labelName: item.options
        }));
      }
    },
    //加载归属人列表
    async selectUser() {
      const {data: res} = await this.$http.post("/system/departmentUtils/getUserListByMap/", {});
      if (res.success) {
        this.options_user = res.data;
      } else {
        return this.$message.error("系统通知信息编辑失败:" + res.message);
      }
    },
    //全选功能
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log("******************************", val);
    },
    //导出
    async batchExportExcel() {
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请至少选择一条记录');
      }
      const resourceIds = this.multipleSelection.map(row => row.resourceId);
      try {
        const res = await axios.request({
          url: 'http://47.99.186.44:8990/customer/excelBatch',
          method: 'post',
          responseType: 'blob',
          headers: {'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)},
          // 直接发送resourceIds数组
          data: resourceIds
        });
        if (res.headers["content-type"] === "application/json") {
          return this.$message.error(
              "Subject does not have permission [user:export]"
          );
        }
        const data = res.data;
        let url = window.URL.createObjectURL(data);
        const a = document.createElement("a");
        document.body.appendChild(a);
        a.href = url;
        a.download = "批量导出客户.xls";
        a.click();
        window.URL.revokeObjectURL(url);
      } catch (error) {
        console.error('批量导出时出错', error);
        this.$message.error('批量导出时遇到异常，请检查网络或联系管理员');
      }
    },
    //转入公海
    async insertHigh_seas_clientList(id) {
      try {
        // 确认弹窗
        const confirm = await this.$confirm(
            "此操作将把该资源转入公海, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消转入公海操作"
          });
        });
        if (confirm) {
          // 发送请求
          const response = await this.$http.post("/highSeasClient/toHighSeas", {
            id: [id]
          });
          // 检查响应结果
          if (response.data.data > 0) {
            this.$message.success('加入公海成功');
            // 重新获取资源列表，以显示更新后的数据
            await this.getClientList();
          } else {
            this.$message.error(response.data.message || '加入公海失败');
          }
        }
      } catch (error) {
        // 处理异常
        if (error.response) {
          // 后端返回的错误
          this.$message.error(`加入公海失败：${error.response.data.message || '未知错误'}`);
        } else if (error.request) {
          // 请求未收到响应（网络错误）
          this.$message.error('网络错误，请检查网络连接');
        } else {
          // 其他错误
          console.error('加入公海时出错', error);
          this.$message.error('加入公海时遇到异常，请检查网络或联系管理员');
        }
      }
    },
    //批量转入公海
    async batchTransferToOpenSea() {
      // 检查是否选中了记录
      if (this.multipleSelection.length === 0) {
        return this.$message.warning('请至少选择一条记录');
      }
      try {
        // 确认弹窗
        const confirm = await this.$confirm(
            "此操作将把选中的资源转入公海, 是否继续?",
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
        ).catch(() => {
          this.$message({
            type: "info",
            message: "已取消转入公海操作"
          });
          return false; // 用户取消操作
        });
        if (confirm) {
          // 提取资源 ID
          const resourceIds = this.multipleSelection.map(row => row.resourceId);
          // 发送批量请求
          const response = await this.$http.post("/highSeasClient/toHighSeas", {
            id: resourceIds
          });
          // 处理响应结果
          if (response.data.data > 0) {
            const successCount = response.data.data; // 获取成功处理的记录数
            if (successCount === this.multipleSelection.length) {
              this.$message.success(`全部 ${successCount} 条记录成功转入公海`);
            } else if (successCount > 0) {
              this.$message.warning(
                  `${successCount} 条记录成功转入公海，${this.multipleSelection.length - successCount} 条记录失败`
              );
            } else {
              this.$message.error('批量转入公海失败');
            }
            // 重新获取资源列表
            await this.getClientList();
          } else {
            this.$message.error(response.data.message || '批量转入公海失败');
          }
        }
      } catch (error) {
        // 处理异常
        if (error.response) {
          this.$message.error(`批量转入公海失败：${error.response.data.message || '未知错误'}`);
        } else if (error.request) {
          this.$message.error('网络错误，请检查网络连接');
        } else {
          console.error('批量转入公海时出错', error);
          this.$message.error('批量转入公海时遇到异常，请检查网络或联系管理员');
        }
      }
    },
    //复制电话号码A
    copyPhoneA(phoneA) {
      const textarea = document.createElement('textarea');
      textarea.value = phoneA;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        const successful = document.execCommand('copy');
        if (successful) {
          this.$message.success('微信号复制成功');
        } else {
          this.$message.error('微信号复制失败');
        }
      } catch (err) {
        this.$message.error('微信号复制失败');
      }
      document.body.removeChild(textarea);
    },
    //改变页码
    handleSizeChange(newSize) {
      this.queryMap.pageSize = newSize;
      this.getClientList();
    },
    //翻页
    handleCurrentChange(current) {
      this.queryMap.pageNum = current;
      this.getClientList();
    },
    //查询客户
    searchClient() {
      this.queryMap.pageNum = 1;
      this.getTime();
      this.getClientList();
    },
    //格式化时间
    formatToMySQLDate(date) {
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');  // 补充月份两位
      const day = date.getDate().toString().padStart(2, '0');  // 补充日期两位
      return `${year}-${month}-${day}`;
    },
    getTime() {
      if (this.value2 != null && this.value2.length === 2) {
        console.log("时间：", this.value2);
        // 格式化开始和结束时间
        this.queryMap.startTime = this.formatDate(this.value2[0], false); // 开始日期
        this.queryMap.endTime = this.formatDate(this.value2[1], true);    // 结束日期
      } else {
        this.queryMap.startTime = "";
        this.queryMap.endTime = "";
      }
    },
    //默认时间
    defaultTime() {
      const end = new Date();
      const start = new Date();
      start.setTime(start.getTime() - 3600 * 1000 * 24 * 2);
      end.setTime(end.getTime());
      this.value2 = [start, end]; // 重置为最近一周
      this.getTime()
    },
    //定义一个格式化时间的函数（格式为 yyyy-MM-dd）
    formatDate(date, isEnd) {
      if (date != null) {
        let formattedDate = new Date(date); // 复制一份新的日期对象，避免修改原始日期
        if (isEnd) {
          // 对结束时间加一天，以确保区间包括结束日期当天
          formattedDate.setDate(formattedDate.getDate() + 1);
        }
        const year = formattedDate.getFullYear();
        const month = ('0' + (formattedDate.getMonth() + 1)).slice(-2);
        const day = ('0' + formattedDate.getDate()).slice(-2);
        return `${year}-${month}-${day}`;
      }
      return null;
    },
    //上传前校验
    beforeUpload(file) {
      // 文件大小校验（500KB）
      const isLt500KB = file.size / 1024 / 1024 < 0.5;
      if (!isLt500KB) {
        this.$message.error('文件大小不能超过 500KB!');
      }
      //文件类型校验
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file.type === 'application/vnd.ms-excel';
      if (!isExcel) {
        this.$message.error('只能上传 .xls 或 .xlsx 格式的文件');
      }
      return isExcel && isLt500KB; // 返回值决定是否继续上传
    },
    // 删除文件时的回调
    handleRemove(file, fileList) {
      console.log('删除文件:', file);
      console.log('文件列表:', fileList);
    },
    // 预览文件时的回调
    handlePreview(file) {
      console.log('预览文件:', file);
    },
    // 上传成功回调
    handleSuccess(response, file, fileList) {
      console.log('上传成功:', response);
      console.log('文件:', file);
      console.log('文件列表:', fileList);
    },
    handleChange(file, fileList) {
      this.fileList = fileList.slice(-1);
      this.excelFile = file;
    },
    // 上传失败回调
    handleError(err, file, fileList) {
      console.error('上传失败:', err);
      console.log('文件:', file);
      console.log('文件列表:', fileList);
    },
    //下载模板
    async downloadTemplate() {
      const confirmResult = await this.$confirm('标红的列必填', '下载提醒！！！', {
        confirmButtonText: '确定下载',
        cancelButtonText: '取消下载',
        type: 'warning'
      }).catch(() => {
        this.$message.info('已取消下载操作');
      })
      if (confirmResult) {
        const $this = this;
        const res = axios.request({
          url: "http://47.99.186.44:8990/template/download",
          method: "post",
          responseType: "blob",
          headers: {
            'Authorization': LocalStorage.get(LOCAL_KEY_XINGUAN_ACCESS_TOKEN)
          },
          data: {
            templateId: "file:/www/wwwroot/danebCRM/backEnd/client/static/Client.xlsx"
          }
        })
            .then(res => {
              if (res.headers["content-type"] === "application/json") {
                return $this.$message.error(
                    "Subject does not have permission [class:export]"
                );
              }
              const data = res.data;
              let url = window.URL.createObjectURL(data);
              const a = document.createElement("a");
              document.body.appendChild(a);
              a.href = url;
              a.download = "客户模版.xlsx";
              a.click();
              window.URL.revokeObjectURL(url);
            })
            .catch(error => {
              console.error("下载出现错误：", error);
              this.$message.error("文件下载失败，请稍后再试");
            });
      }
    },
    //外呼方法
    async outPhone() {
      if (this.appId == null || this.appId == "") {
        return this.$message.error("账户信息错误：应用key");
      }
      if (this.callerNbr == null || this.callerNbr == "") {
        return this.$message.error("账户信息错误：手机号");
      }
      if (this.calleeNbr == null || this.calleeNbr == "") {
        return this.$message.error("外呼号码不可为空");
      }
      if (this.bindNbr == null || this.bindNbr == "") {
        return this.$message.error("账户信息错误：中间号");
      }
      let ifOpen = await this.getSign();
      if (ifOpen == false) {
        // this.btnLoading = false;
        // this.btnDisabled = false;
        return;
      }
      await this.ready();
    },
    //外呼
    async ready() {
      axios.post("https://yx.jsyouxiao.com/apis/public/apiCall/call", {
        "appId": this.appId,
        "callerNbr": this.callerNbr,
        "calleeNbr": this.calleeNbr,
        "bindNbr": this.bindNbr,
        "notifyUrl": this.notifyUrl,
        "sign": this.sign,
      }).then(async res => {
        if (res != null) {
          if (res.data.code == '200') {
            console.log(res.data);
            let sessionId = res.data.data.sessionId;
            if (sessionId != null) {
              const {data: res2} = await this.$http.post("/comcentre/call/saveLog", {
                sessionId: sessionId,
                bindNbr: this.bindNbr,
                callerNbr: this.callerNbr,
                calleeNbr: this.calleeNbr
              });
              console.log(res2);
              if (!res2.success) {
                console.log(res.data);
                return this.$message.error(res2.data.msg);
              }
            }
            return this.$message.info(res.data.msg);
          } else if (res.data.code == '500') {
            return this.$message.error(res.data.msg);
          }
        }
      });
    },
    //外呼
    async getSign() {
      const {data: res} = await this.$http.post("/comcentre/call/getSign", {
        appId: this.appId,
        callerNbr: this.callerNbr,
        calleeNbr: this.calleeNbr,
        notifyUrl: this.notifyUrl,
        bindNbr: this.bindNbr
      })
      if (!res.success) {
        this.$message.error("错误信息:" + res.data);
        return false;
      }
      this.sign = res.data;
    },
    //外呼
    async getCallerNbr() {
      const {data: res} = await this.$http.get("/comcentre/call/getCallerNbr");
      if (res != null) {
        this.callerNbr = res.data;
      }
    },
    //外呼
    async getBindNbr() {
      const {data: res} = await this.$http.get("/comcentre/call/getBindNbr");
      if (res != null) {
        this.bindNbr = res.data;
      }
    },
    //外呼
    async getAppId() {
      const {data: res} = await this.$http.get("/comcentre/call/getAppId");
      if (res != null) {
        this.appId = res.data;
      }
    },
  },
  created() {
    this.getAccountNameList();
    //外呼
    this.getCallerNbr();
    this.getBindNbr();
    this.getAppId();
    this.defaultTime();
    this.getAllIndustryList();
    this.getAllClientType();
    this.selectUser();
    this.getAllSource();
    this.getAllClientStatus();
    this.getAllLabelInfo();
    this.changeAccountName();
  }
}
</script>

<style scoped>
.hint {
  margin-left: 2vh;
  font-weight: 400;
  font-size: 12px;
  color: red;
}

.dataDict {
  border: none;
  background-color: #fff;
  position: absolute;
  padding: .8vh 0;
  left: 17.2vh;
  font-size: 18px;
}

.popups {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0%;
  left: 0%;
  background-color: #00000042;
  z-index: 100;
}

.popups .el-main {
  background-color: #fff;
  margin: 15vh auto;
}

.popups .el-main .header {
  display: flex;
  justify-content: center;
  margin-bottom: 2vh;
}

.popups .el-main .header button {
  flex-shrink: 0; /* 防止收缩 */
  font-size: 3vh;
  height: 4.6vh;
  border: none;
}

.el-row {
  margin-bottom: 20px;

  &:last-child {
    margin-bottom: 0;
  }
}

.el-row .el-col {
  font-size: 14px;
}

.el-row .el-col label {
  color: #5e6d82;
}
</style>